<template>
  <view class="nature-sound-page">
    <!-- 导航栏 -->
    <u-navbar :title="pageTitle" :placeholder="true" back-text="">
      <view class="u-nav-slot" slot="left" @click="$returnPage()">
        <u-icon name="arrow-left" size="20" color="#333"></u-icon>
      </view>
    </u-navbar>

    <!-- 主要内容区域 -->
    <view class="main-content">

      <!-- 声音列表 -->
      <view class="sound-list">
        <view 
          v-for="(item, index) in soundList" 
          :key="item.id || index"
          class="sound-item"
          @click="enterPlayerMode(item, index)"
        >
          <view class="sound-icon">
            <u-icon :name="item.imageUrl || 'bell'" size="28" :color="currentPlaying === index ? '#25772f' : '#666'"></u-icon>
          </view>
          <view class="sound-info">
            <view class="sound-name">{{ item.name || item.mediaName || '未知音乐' }}</view>
            <!-- 移除描述，添加时长、地点和采集时间 -->
            <view class="sound-meta">
              <text class="meta-item" v-if="item.mediaTime">
                <u-icon name="clock" size="12" color="#999"></u-icon>
                {{ formatDuration(item.mediaTime) }}
              </text>
              <text class="meta-item" v-if="item.address">
                <u-icon name="map-marked" size="12" color="#999"></u-icon>
                {{ item.address }}
              </text>
              <text class="meta-item" v-if="item.createdAt">
                <u-icon name="calendar" size="12" color="#999"></u-icon>
                采集于 {{ formatDate(item.createdAt) }}
              </text>
            </view>
          </view>
          <view class="sound-actions">
            <!-- 修改调用方式，使用索引获取数据 -->
            <view class="action-btn" @click.stop="saveMusicByIndex(index)" v-if="item && item.id && !item.isFavorite">
              <u-icon name="heart" size="20" color="#999"></u-icon>
            </view>
            <view class="action-btn saved" @click.stop="removeSavedMusicByIndex(index)" v-else-if="item && item.id && item.isFavorite">
              <u-icon name="heart-fill" size="20" color="#25772f"></u-icon>
            </view>
            <view class="play-button">
              <u-icon 
                :name="currentPlaying === index ? 'pause-circle' : 'play-circle'" 
                size="24" 
                :color="currentPlaying === index ? '#25772f' : '#999'"
              ></u-icon>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多状态 -->
      <u-loadmore :status="page_loading" loading-text="数据加载中" loadingIcon="spinner" 
        v-if="!(page_loading == 'nomore' && $u.test.isEmpty(soundList))"/>

      <!-- 播放控制区域 -->
      <view class="player-section" v-if="currentSound">
        <view class="player-info">
          <view class="current-sound-name">{{ currentSound.name || currentSound.mediaName || '未知音乐' }}</view>
          <view class="current-sound-desc">{{ currentSound.description || currentSound.address || '暂无描述' }}</view>
        </view>
        <view class="player-controls">
          <view class="control-btn" @click="previousSound">
            <u-icon name="skip-back" size="20" color="#25772f"></u-icon>
          </view>
          <view class="control-btn main-play-btn" @click="togglePlay">
            <u-icon 
              :name="isPlaying ? 'pause' : 'play'" 
              size="24" 
              color="#fff"
            ></u-icon>
          </view>
          <view class="control-btn" @click="nextSound">
            <u-icon name="skip-forward" size="20" color="#25772f"></u-icon>
          </view>
        </view>
        <view class="volume-control">
          <u-icon name="volume-down" size="16" color="#666"></u-icon>
          <slider 
            class="volume-slider" 
            :value="volume" 
            @change="changeVolume"
            activeColor="#25772f"
            block-size="12"
          />
          <u-icon name="volume-up" size="16" color="#666"></u-icon>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentPlaying: -1,
      currentSound: null,
      isPlaying: false,
      volume: 50,
      audioContext: null,
      soundList: [],
      page_loading: 'loading',
      searchForm: {
        page: 1,
        size: 10,
      },
      pageType: 'normal', // normal: 普通音乐列表, favorites: 个人收藏
      pageTitle: '自然之声' // 页面标题
    }
  },
  
  onLoad(options) {
	  console.log("====>",options)
    // 检查页面类型参数
    if (options.type === 'favorites') {
      this.pageType = 'favorites'
      this.pageTitle = '个人收藏'
    }
    
    // 创建音频上下文
    this.audioContext = uni.createInnerAudioContext()
    this.audioContext.autoplay = false
    this.audioContext.loop = true
    
    // 监听音频事件
    this.audioContext.onPlay(() => {
      this.isPlaying = true
    })
    
    this.audioContext.onPause(() => {
      this.isPlaying = false
    })
    
    this.audioContext.onStop(() => {
      this.isPlaying = false
      this.currentPlaying = -1
    })
    
    this.audioContext.onError((res) => {
      console.error('音频播放出错:', res)
      uni.showToast({
        title: '音频播放失败',
        icon: 'none'
      })
    })
    
    // 初始化加载音乐列表
    this.getMusicList(true)
  },
  
  onPullDownRefresh() {
    this.getMusicList(true)
  },
  
  async onReachBottom() {
    if (this.page_loading !== 'loading') {
      await this.getMusicList()
    }
  },
  
  onUnload() {
    // 页面销毁时清理音频资源
    if (this.audioContext) {
      this.audioContext.destroy()
    }
  },
  
  methods: {
    // 格式化时长（秒转为 mm:ss 格式）
    formatDuration(seconds) {
      if (!seconds) return '00:00';
      
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      
      // 处理不同格式的日期字符串
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return ''; // 无效日期
      
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 通过索引保存音乐
    saveMusicByIndex(index) {
      const music = this.soundList[index];
      console.log('通过索引保存音乐:', index, music);
      this.saveMusic(music);
    },
    
    // 通过索引取消保存音乐
    removeSavedMusicByIndex(index) {
      const music = this.soundList[index];
      console.log('通过索引取消保存音乐:', index, music);
      this.removeSavedMusic(music);
    },
    
    // 播放声音
    playSound(sound, index) {
      console.log('播放声音:', sound, '索引:', index)
      
      if (this.currentPlaying === index) {
        // 如果是当前播放的声音，则暂停/继续
        this.togglePlay()
      } else {
        // 播放新的声音
        this.currentSound = {
          name: sound.mediaName || sound.title || sound.name || '未知音乐',
          description: sound.remark || sound.description || sound.address || '暂无描述'
        }
        this.currentPlaying = index
        
        // 检查音频URL，支持多个字段名
        const audioUrl = sound.mediaUrl || sound.audioUrl || sound.url || sound.mp3Url
        console.log('音频URL:', audioUrl)
        
        if (audioUrl) {
          this.audioContext.src = audioUrl
          this.audioContext.play()
        } else {
          console.error('未找到音频URL，数据结构:', sound)
          uni.showToast({
            title: '音频文件不存在',
            icon: 'none'
          })
        }
      }
    },
    
    // 进入单页播放器模式
    enterPlayerMode(sound, index) {
      console.log(1111,sound,index)
      // 停止当前播放
      if (this.audioContext) {
        this.audioContext.stop()
      }
      
      // 传递当前音乐列表数据到播放器页面
      const musicData = this.soundList.map(item => {
        return {
          id: item.id,
          name: item.mediaName || item.name || item.title || '未知音乐',
          description: item.remark || item.description || item.address || '暂无描述',
          icon: item.imageUrl,
          url: item.mediaUrl || item.audioUrl || item.url || item.mp3Url,
          title: item.mediaName || item.name || item.title || '未知音乐',
          audioUrl: item.mediaUrl || item.audioUrl || item.url || item.mp3Url
        }
      })
      
      // 跳转到播放器页面
      uni.navigateTo({
        url: `/packageB/nature-sound/player?soundData=${encodeURIComponent(JSON.stringify(musicData))}&currentIndex=${index}`
      })
    },
    
    // 切换播放/暂停
    togglePlay() {
      if (this.isPlaying) {
        this.audioContext.pause()
      } else {
        if (this.currentSound) {
          this.audioContext.play()
        }
      }
    },
    
    // 上一首
    previousSound() {
      if (this.currentPlaying > 0) {
        this.playSound(this.soundList[this.currentPlaying - 1], this.currentPlaying - 1)
      } else {
        this.playSound(this.soundList[this.soundList.length - 1], this.soundList.length - 1)
      }
    },
    
    // 下一首
    nextSound() {
      if (this.currentPlaying < this.soundList.length - 1) {
        this.playSound(this.soundList[this.currentPlaying + 1], this.currentPlaying + 1)
      } else {
        this.playSound(this.soundList[0], 0)
      }
    },
    
    // 改变音量
    changeVolume(e) {
      this.volume = e.detail.value
      if (this.audioContext) {
        this.audioContext.volume = this.volume / 100
      }
    },
    
    // 获取音乐列表
    getMusicList(isRefresh = false) {
      return new Promise((resolve, reject) => {
        if (isRefresh) {
          this.searchForm.page = 1
          this.soundList = []
          this.page_loading = 'loading'
        }
        
        // 根据页面类型选择不同的接口
        let apiUrl, apiMethod, requestData
        
        if (this.pageType === 'favorites') {
          // 个人收藏模式
          apiUrl = 'system/favorite/music/user'
          apiMethod = 'GET'
          requestData = {
            pageNum: this.searchForm.page,
            pageSize: this.searchForm.size,
          }
        } else {
          // 普通音乐列表模式
          apiUrl = 'system/media/mediaList'
          apiMethod = 'GET'
        requestData = {
            pageNum: this.searchForm.page,
            pageSize: this.searchForm.size,
          }
        }
        
        this.$http.to_http(apiUrl, requestData, apiMethod, isRefresh ? '加载中' : false).then(res => {
          console.log('接口返回数据:', res)
          res = res.data
          console.log('解析后数据:', res)
          
          if (res.code !== 200) {
            uni.showToast({
              title: res.msg || '获取数据失败',
              icon: 'none'
            })
            this.page_loading = 'nomore'
            return reject(res)
          }
          
          // 根据不同模式处理数据结构
          let newList = []
          if (this.pageType === 'favorites') {
            // 收藏数据结构不同，需要转换
            newList = (res.rows || []).map(item => {
              // 收藏项目包含 media 字段
              const media =  item
              return {
                id: media.mediaId,
                mediaName: media.title,
                remark: media.description,
                imageUrl: media.coverUrl,
                mediaUrl:  media.url,
                address: media.description,
                mediaTime: media.duration,
                createdAt: media.createTime,
                isFavorite: true, // 收藏列表中的都是已收藏
                favoriteId: item.id// 收藏记录的ID
              }
            })
          } else {
            // 使用 rows 字段而不是 data 字段
            newList = res.rows || res.data || []
          }
          
          console.log('新数据列表:', newList)
          
          if (isRefresh) {
            this.soundList = newList
          } else {
            this.soundList = [...this.soundList, ...newList]
          }
          
          // 处理分页状态
          if (newList.length > 0 && newList.length >= this.searchForm.size) {
            this.searchForm.page++
            this.page_loading = 'loadmore'
          } else {
            this.page_loading = 'nomore'
          }
          
          // 格式化音乐数据，使用正确的字段名
          this.soundList = this.soundList.map(item => {
            console.log('原始数据项:', item)
            return {
              ...item,
              // 确保id字段可用
              id: item.id || item.mediaId || item.musicId || item.audioId,
              name: item.mediaName || item.name || item.title || '未知音乐',
              description: item.remark || item.description || item.address || '暂无描述',
              icon: item.imageUrl || item.icon || 'bell',
              url: item.mediaUrl || item.audioUrl || item.url || item.mp3Url || '',
              // 保留时长、地址和采集时间字段
              mediaTime: item.mediaTime,
              address: item.address,
              createdAt: item.createdAt,
              // 保持 isFavorite 字段
              isFavorite: item.isFavorite !== undefined ? item.isFavorite : false
            }
          })

          console.log('格式化后的音乐列表:', this.soundList)
          
          // 只有普通模式才需要检查收藏状态
          if (this.pageType !== 'favorites') {
            this.checkFavoriteStatus()
          }
          
          if (isRefresh) {
            uni.stopPullDownRefresh()
          }
          
          resolve(res)
        }).catch(err => {
          console.error('获取数据失败:', err)
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          })
          this.page_loading = 'nomore'
          
          if (isRefresh) {
            uni.stopPullDownRefresh()
          }
          
          reject(err)
        })
      })
    },
    
    // 收藏音乐
    saveMusic(music) {
      console.log('调用 saveMusic，参数:', music);
      
      // 添加检查确保 music 对象存在
      if (!music) {
        console.error('saveMusic 方法接收到的 music 参数为 undefined');
        uni.showToast({
          title: '无效的音乐数据',
          icon: 'none'
        })
        return
      }
      
      console.log('music 对象内容:', JSON.stringify(music));
      
      if (!music.id) {
        console.error('music 对象缺少 id 属性:', music);
        uni.showToast({
          title: '无效的音乐数据',
          icon: 'none'
        })
        return
      }
      
      const saveData = {
        mediaId: music.id,
        mediaType: 'audio'
      }
      
      console.log('发送收藏请求，数据:', saveData);
      
      this.$http.to_http('system/favorite/music', saveData, 'POST', '收藏中').then(res => {
        res = res.data
        console.log('收藏请求返回结果:', res);
        if (res.code === 200) {
          uni.showToast({
            title: '收藏成功',
            icon: 'success'
          })
          
          // 更新本地状态
          const index = this.soundList.findIndex(item => item.id === music.id)
          if (index !== -1) {
            // 使用 $set 确保响应式更新
            this.$set(this.soundList[index], 'isFavorite', true);
            this.$set(this.soundList[index], 'favoriteId', res.data?.id || res.data);
            console.log('更新后的 soundList:', this.soundList);
          } else {
            console.warn('未在 soundList 中找到对应的音乐项');
          }
        } else {
          uni.showToast({
            title: res.msg || '收藏失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        console.error('收藏音乐失败:', err)
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
      })
    },
    
    // 取消收藏音乐
    removeSavedMusic(music) {
      console.log('调用 removeSavedMusic，参数:', music);
      
      // 添加检查确保 music 对象存在
      if (!music) {
        console.error('removeSavedMusic 方法接收到的 music 参数为 undefined');
        uni.showToast({
          title: '无效的收藏数据',
          icon: 'none'
        })
        return
      }
      
      console.log('music 对象内容:', JSON.stringify(music));
      
      const musicId = music.id || music.mediaId || music.musicId || music.audioId
      
      if (!musicId) {
        console.error('music 对象缺少有效的 ID 属性:', music);
        uni.showToast({
          title: '无效的收藏数据',
          icon: 'none'
        })
        return
      }
      
      const deleteUrl ='system/favorite/music/deleteById'
      console.log('发送取消收藏请求，URL:', deleteUrl);
      
      this.$http.to_http(deleteUrl, {mediaId:musicId}, 'POST', '取消收藏中').then(res => {
        res = res.data
        console.log('取消收藏请求返回结果:', res);
        if (res.code === 200) {
          uni.showToast({
            title: '已取消收藏',
            icon: 'success'
          })
          
          // 更新本地状态
          const index = this.soundList.findIndex(item => 
            (item.id || item.mediaId || item.musicId || item.audioId) === musicId
          )
          
          if (index !== -1) {
            if (this.pageType === 'favorites') {
              // 收藏模式下直接从列表中移除
              this.soundList.splice(index, 1);
              // 强制更新视图
              this.$set(this, 'soundList', [...this.soundList]);
            } else {
              // 普通模式下更新状态
              this.$set(this.soundList[index], 'isFavorite', false);
            }
            console.log('更新后的 soundList:', this.soundList);
          } else {
            console.warn('未在 soundList 中找到对应的音乐项');
          }
        } else {
          uni.showToast({
            title: res.msg || '取消收藏失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        console.error('取消收藏音乐失败:', err)
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        })
      })
    },
    
    // 检查收藏状态
    checkFavoriteStatus() {
      if (this.soundList.length === 0) {
        return
      }
      
      // 获取当前用户的收藏列表
      this.$http.to_http('system/favorite/music', {}, 'GET', false).then(res => {
        res = res.data
        if (res.code === 200 && res.data) {
          const favoriteList = res.data || []
          
          // 更新音乐列表的收藏状态
          this.soundList = this.soundList.map(music => {
            const favorite = favoriteList.find(fav => 
              fav.mediaId === music.id && fav.mediaType === 'audio'
            )
            
            return {
              ...music,
              isFavorite : !!favorite,
              favoriteId: favorite?.id
            }
          })
          
          // 强制触发视图更新
          this.$set(this, 'soundList', [...this.soundList]);
          console.log('更新收藏状态后的音乐列表:', this.soundList)
        }
      }).catch(err => {
        console.error('获取收藏状态失败:', err)
        // 不显示错误提示，静默失败
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.nature-sound-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.u-nav-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.1);
}

.main-content {
  padding: 0 30rpx;
}

.sound-list {
  margin: 40rpx auto;
}

.sound-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  margin-bottom: 20rpx;
  background: #fff;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
  }
  
  .sound-icon {
    margin-right: 20rpx;
  }
  
  .sound-info {
    flex: 1;
    min-width: 0; // 防止内容溢出
    
    .sound-name {
      font-size: 28rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 8rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .sound-desc {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
    }
    
    .sound-meta {
  display: flex;
  align-items: center;
  margin-top: 10rpx;

  .meta-item {
    font-size: 20rpx;
    color: #999;
    margin-right: 20rpx;
    display: flex;
    align-items: center;

    &:last-child {
      margin-right: 0;
    }

    .u-icon {
      margin-right: 5rpx;
    }
  }
}
  }
  
  .sound-actions {
    display: flex;
    align-items: center;
    gap: 15rpx;
    
    .action-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      background: #f5f5f5;
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.95);
      }
      
      &.saved {
        background: rgba(37, 119, 47, 0.1);
      }
    }
    
    .play-button {
      margin-left: 0;
    }
  }
}

.player-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-radius: 30rpx 30rpx 0 0;
  padding: 40rpx 30rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  
  .player-info {
    text-align: center;
    margin-bottom: 40rpx;
    
    .current-sound-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .current-sound-desc {
      font-size: 24rpx;
      color: #666;
    }
  }
  
  .player-controls {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40rpx;
    
    .control-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      background: #f5f5f5;
      margin: 0 20rpx;
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.95);
      }
      
      &.main-play-btn {
        width: 100rpx;
        height: 100rpx;
        background: #25772f;
        margin: 0 30rpx;
      }
    }
  }
  
  .volume-control {
    display: flex;
    align-items: center;
    
    .volume-slider {
      flex: 1;
      margin: 0 20rpx;
    }
  }
}

/* 响应式设计 */
@media (max-width: 750rpx) {
  .sound-item {
    padding: 25rpx;
  }
  
  .player-section {
    padding: 30rpx 20rpx;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.sound-item {
  animation: fadeIn 0.3s ease-out;
}
</style>